<?php

namespace App\Models\Es;
use DesignMyNight\Elasticsearch\EloquentBuilder;
use DesignMyNight\Elasticsearch\QueryBuilder;
use DesignMyNight\Elasticsearch\Searchable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder as DatabaseEloquentBuilder;
use Illuminate\Database\Query\Builder as DatabaseQueryBuilder;


class EsBaseModel extends Model
{
    public $incrementing = false;

    protected $primaryKey = '_id';

    use Searchable;

    public function get_idAttribute()
    {
        return $this->attributes['_id'] ?? ($this->attributes['id'] ?? '');
    }

    public function getIdAttribute()
    {
        return $this->attributes['_id'] ?? ($this->attributes['id'] ?? '');
    }

    /**
     * Create a new Eloquent builder for the model.
     *
     * @param  \Illuminate\Database\Query\Builder  $query
     * @return \DesignMyNight\Elasticsearch\EloquentBuilder|\Illuminate\Database\Eloquent\Builder
     */
    public function newEloquentBuilder($query)
    {
        switch ($this->getConnectionName()) {
            case static::getElasticsearchConnectionName():
                $builder = new EloquentBuilder($query);
                break;
            default:
                $builder = new DatabaseEloquentBuilder($query);
        }

        return $builder;
    }

    /**
     * Get a new query builder instance for the connection.
     *
     * @return \Illuminate\Database\Query\Builder
     */
    protected function newBaseQueryBuilder()
    {
        $connection = $this->getConnection();
        switch ($this->getConnectionName()) {
            case static::getElasticsearchConnectionName():
                $builder = new QueryBuilder($connection, $connection->getQueryGrammar(), $connection->getPostProcessor());
                break;
            default:
                $builder = new DatabaseQueryBuilder($connection, $connection->getPostProcessor());
        }

        return $builder;
    }

    /**
     * 使用Scroll获取数据
     * @param int $size
     * @return \DesignMyNight\Elasticsearch\EloquentBuilder
     */
    public static function usingScroll(int $size=10000){
        return self::newElasticsearchQuery()->usingScroll($size);
    }

    /**
     * @return \DesignMyNight\Elasticsearch\EloquentBuilder
     */
    public static function query(): EloquentBuilder
    {
        return self::newElasticsearchQuery()->usingScroll(10000);
    }
}
